using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using System.Text.RegularExpressions;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 章节连续性服务 - 处理章节衔接和结尾完整性
    /// </summary>
    public class ChapterContinuityService
    {
        private readonly ILogger<ChapterContinuityService> _logger;
        private readonly IAIService _aiService;

        public ChapterContinuityService(
            ILogger<ChapterContinuityService> logger,
            IAIService aiService)
        {
            _logger = logger;
            _aiService = aiService;
        }

        /// <summary>
        /// 获取前一章末尾内容用于衔接（300字）
        /// </summary>
        public string GetPreviousChapterEnding(string previousChapterContent, int targetLength = 300)
        {
            if (string.IsNullOrEmpty(previousChapterContent))
                return string.Empty;

            try
            {
                // 移除多余的空白字符
                var cleanContent = previousChapterContent.Trim();
                
                // 如果内容太短，直接返回
                if (cleanContent.Length <= targetLength)
                    return cleanContent;

                // 从末尾开始截取指定长度
                var ending = cleanContent.Substring(cleanContent.Length - targetLength);
                
                // 尝试从完整句子开始
                var sentences = SplitIntoSentences(ending);
                if (sentences.Count > 1)
                {
                    // 去掉第一个可能不完整的句子
                    ending = string.Join("", sentences.Skip(1));
                }

                _logger.LogInformation($"提取前章末尾内容，长度: {ending.Length}");
                return ending;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "提取前章末尾内容失败");
                return string.Empty;
            }
        }

        /// <summary>
        /// 检查章节结尾是否完整
        /// </summary>
        public async Task<ChapterEndingAnalysis> AnalyzeChapterEndingAsync(string chapterContent)
        {
            try
            {
                var analysis = new ChapterEndingAnalysis
                {
                    OriginalContent = chapterContent,
                    AnalyzedAt = DateTime.Now
                };

                if (string.IsNullOrEmpty(chapterContent))
                {
                    analysis.IsComplete = false;
                    analysis.Issues.Add("章节内容为空");
                    return analysis;
                }

                // 获取章节末尾部分
                var ending = GetChapterEnding(chapterContent, 500);
                analysis.EndingContent = ending;

                // 基础完整性检查
                analysis.IsComplete = CheckBasicCompleteness(ending);
                
                if (!analysis.IsComplete)
                {
                    analysis.Issues.AddRange(IdentifyCompletenessIssues(ending));
                }

                // 使用AI进行深度分析
                var aiAnalysis = await PerformAIEndingAnalysisAsync(ending);
                analysis.AIAnalysis = aiAnalysis;
                
                // 如果AI认为不完整，更新分析结果
                if (aiAnalysis.Contains("不完整") || aiAnalysis.Contains("需要补全"))
                {
                    analysis.IsComplete = false;
                    analysis.Issues.Add("AI分析认为结尾不完整");
                }

                _logger.LogInformation($"章节结尾分析完成，是否完整: {analysis.IsComplete}");
                return analysis;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分析章节结尾失败");
                return new ChapterEndingAnalysis
                {
                    OriginalContent = chapterContent,
                    IsComplete = false,
                    Issues = new List<string> { $"分析失败: {ex.Message}" },
                    AnalyzedAt = DateTime.Now
                };
            }
        }

        /// <summary>
        /// 补全不完整的章节结尾
        /// </summary>
        public async Task<string> CompleteChapterEndingAsync(
            string incompleteChapter, 
            string chapterOutline, 
            ChapterContext context)
        {
            try
            {
                _logger.LogInformation("开始补全章节结尾");

                var prompt = BuildEndingCompletionPrompt(incompleteChapter, chapterOutline, context);
                
                var completion = await _aiService.GenerateTextAsync(prompt, 1000, 0.8f);
                
                if (string.IsNullOrEmpty(completion))
                {
                    _logger.LogWarning("AI生成的结尾补全内容为空");
                    return incompleteChapter;
                }

                // 清理和格式化补全内容
                var cleanCompletion = CleanCompletionContent(completion);
                
                // 合并原内容和补全内容
                var completeChapter = incompleteChapter.TrimEnd() + "\n\n" + cleanCompletion;

                _logger.LogInformation($"章节结尾补全完成，新增内容长度: {cleanCompletion.Length}");
                return completeChapter;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "补全章节结尾失败");
                return incompleteChapter;
            }
        }

        /// <summary>
        /// 生成带有前章衔接的章节内容
        /// </summary>
        public async Task<string> GenerateChapterWithContinuityAsync(
            string chapterOutline,
            string previousChapterEnding,
            ChapterContext context,
            int targetWordCount = 6500)
        {
            try
            {
                _logger.LogInformation("开始生成带衔接的章节内容");

                var prompt = BuildContinuityChapterPrompt(
                    chapterOutline, previousChapterEnding, context, targetWordCount);

                var content = await _aiService.GenerateTextAsync(prompt, targetWordCount + 500, 0.8f);

                if (string.IsNullOrEmpty(content))
                {
                    _logger.LogWarning("生成的章节内容为空");
                    return string.Empty;
                }

                // 清理和格式化内容
                var cleanContent = CleanChapterContent(content);

                // 检查生成的内容是否有良好的衔接
                var continuityScore = EvaluateContinuity(previousChapterEnding, cleanContent);
                _logger.LogInformation($"章节衔接评分: {continuityScore:F2}");

                return cleanContent;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成带衔接的章节内容失败");
                return string.Empty;
            }
        }

        /// <summary>
        /// 获取章节结尾部分
        /// </summary>
        private string GetChapterEnding(string content, int length = 300)
        {
            if (string.IsNullOrEmpty(content) || content.Length <= length)
                return content;

            return content.Substring(content.Length - length);
        }

        /// <summary>
        /// 基础完整性检查
        /// </summary>
        private bool CheckBasicCompleteness(string ending)
        {
            if (string.IsNullOrEmpty(ending))
                return false;

            // 检查是否以完整的句子结尾
            var lastChar = ending.TrimEnd().LastOrDefault();
            var completionMarks = new[] { '。', '！', '？', '"', '"', '…' };
            
            if (!completionMarks.Contains(lastChar))
                return false;

            // 检查是否有明显的未完成标志
            var incompleteMarkers = new[] { "待续", "未完", "..." };
            if (incompleteMarkers.Any(marker => ending.Contains(marker)))
                return false;

            return true;
        }

        /// <summary>
        /// 识别完整性问题
        /// </summary>
        private List<string> IdentifyCompletenessIssues(string ending)
        {
            var issues = new List<string>();

            if (string.IsNullOrEmpty(ending))
            {
                issues.Add("结尾内容为空");
                return issues;
            }

            var lastChar = ending.TrimEnd().LastOrDefault();
            var completionMarks = new[] { '。', '！', '？', '"', '"', '…' };
            
            if (!completionMarks.Contains(lastChar))
            {
                issues.Add("结尾没有适当的标点符号");
            }

            if (ending.Contains("待续"))
                issues.Add("包含'待续'标记");
            
            if (ending.Contains("未完"))
                issues.Add("包含'未完'标记");
            
            if (ending.EndsWith("..."))
                issues.Add("以省略号结尾，可能不完整");

            // 检查是否在对话中间结束
            var dialogueCount = ending.Count(c => c == '"' || c == '"');
            if (dialogueCount % 2 != 0)
            {
                issues.Add("可能在对话中间结束");
            }

            return issues;
        }

        /// <summary>
        /// AI结尾分析
        /// </summary>
        private async Task<string> PerformAIEndingAnalysisAsync(string ending)
        {
            try
            {
                var prompt = $@"请分析以下章节结尾是否完整：

章节结尾内容：
{ending}

请判断：
1. 这个结尾是否完整？
2. 如果不完整，缺少什么？
3. 是否需要补全？

请简要回答：";

                return await _aiService.GenerateTextAsync(prompt, 300, 0.7f);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "AI结尾分析失败");
                return "AI分析失败";
            }
        }

        /// <summary>
        /// 构建结尾补全提示
        /// </summary>
        private string BuildEndingCompletionPrompt(string incompleteChapter, string outline, ChapterContext context)
        {
            var ending = GetChapterEnding(incompleteChapter, 500);
            
            return $@"请为以下不完整的章节补全结尾：

章节细纲：
{outline}

章节末尾部分（可能不完整）：
{ending}

上下文信息：
- 书名：{context.BookTitle}
- 章节号：第{context.ChapterNumber}章
- 目标字数：{context.TargetWordCount}字

要求：
1. 自然衔接现有内容
2. 完成当前情节段落
3. 为下一章做适当铺垫
4. 确保结尾完整且有意义
5. 补全内容控制在200-500字

请直接输出补全的结尾内容，不要添加任何解释：";
        }

        /// <summary>
        /// 构建带衔接的章节生成提示
        /// </summary>
        private string BuildContinuityChapterPrompt(
            string outline, 
            string previousEnding, 
            ChapterContext context, 
            int targetWordCount)
        {
            return $@"请根据以下信息创作章节内容：

章节细纲：
{outline}

前一章结尾（必须自然衔接）：
{previousEnding}

创作要求：
1. 必须与前一章结尾自然衔接，不能突兀
2. 严格按照章节细纲发展剧情
3. 目标字数：{targetWordCount}字
4. 保持角色性格一致性
5. 确保情节逻辑合理

上下文信息：
- 书名：{context.BookTitle}
- 章节号：第{context.ChapterNumber}章
- 创作风格：{context.WritingStyle}

请创作完整的章节内容：";
        }

        /// <summary>
        /// 清理补全内容
        /// </summary>
        private string CleanCompletionContent(string content)
        {
            if (string.IsNullOrEmpty(content))
                return string.Empty;

            // 移除可能的解释性文字
            var lines = content.Split('\n')
                .Where(line => !line.Trim().StartsWith("补全") && 
                              !line.Trim().StartsWith("以上") &&
                              !line.Trim().StartsWith("注意"))
                .ToList();

            return string.Join("\n", lines).Trim();
        }

        /// <summary>
        /// 清理章节内容
        /// </summary>
        private string CleanChapterContent(string content)
        {
            if (string.IsNullOrEmpty(content))
                return string.Empty;

            // 移除可能的标题和解释
            var cleaned = content.Trim();
            
            // 移除开头的章节标题（如果有）
            if (cleaned.StartsWith("第") && cleaned.Contains("章"))
            {
                var firstLineEnd = cleaned.IndexOf('\n');
                if (firstLineEnd > 0)
                {
                    cleaned = cleaned.Substring(firstLineEnd + 1).Trim();
                }
            }

            return cleaned;
        }

        /// <summary>
        /// 评估章节衔接质量
        /// </summary>
        private double EvaluateContinuity(string previousEnding, string currentChapter)
        {
            if (string.IsNullOrEmpty(previousEnding) || string.IsNullOrEmpty(currentChapter))
                return 0.0;

            var score = 0.0;
            var currentStart = currentChapter.Length > 500 ? currentChapter.Substring(0, 500) : currentChapter;

            // 检查关键词连续性
            var previousWords = ExtractKeywords(previousEnding);
            var currentWords = ExtractKeywords(currentStart);
            var commonWords = previousWords.Intersect(currentWords).Count();
            
            if (previousWords.Count > 0)
            {
                score += (double)commonWords / previousWords.Count * 0.4;
            }

            // 检查情绪连续性
            var previousTone = AnalyzeTone(previousEnding);
            var currentTone = AnalyzeTone(currentStart);
            if (previousTone == currentTone)
            {
                score += 0.3;
            }

            // 检查时间连续性
            if (HasTimeTransition(currentStart))
            {
                score += 0.3;
            }
            else
            {
                score += 0.1; // 直接连续也是好的
            }

            return Math.Min(1.0, score);
        }

        /// <summary>
        /// 提取关键词
        /// </summary>
        private HashSet<string> ExtractKeywords(string text)
        {
            var keywords = new HashSet<string>();
            var words = Regex.Split(text, @"\W+")
                .Where(w => w.Length > 1)
                .Select(w => w.ToLower());

            foreach (var word in words)
            {
                keywords.Add(word);
            }

            return keywords;
        }

        /// <summary>
        /// 分析语调
        /// </summary>
        private string AnalyzeTone(string text)
        {
            if (text.Contains("！") || text.Contains("激动") || text.Contains("愤怒"))
                return "激烈";
            if (text.Contains("？") || text.Contains("疑惑") || text.Contains("困惑"))
                return "疑问";
            if (text.Contains("…") || text.Contains("沉默") || text.Contains("思考"))
                return "沉思";
            
            return "平静";
        }

        /// <summary>
        /// 检查是否有时间转换
        /// </summary>
        private bool HasTimeTransition(string text)
        {
            var timeMarkers = new[] { "第二天", "次日", "过了", "后来", "不久", "片刻", "随后", "接着" };
            return timeMarkers.Any(marker => text.Contains(marker));
        }

        /// <summary>
        /// 分割句子
        /// </summary>
        private List<string> SplitIntoSentences(string text)
        {
            var sentences = new List<string>();
            var sentenceEnders = new[] { '。', '！', '？', '…' };
            
            var currentSentence = "";
            foreach (var ch in text)
            {
                currentSentence += ch;
                if (sentenceEnders.Contains(ch))
                {
                    sentences.Add(currentSentence);
                    currentSentence = "";
                }
            }
            
            if (!string.IsNullOrEmpty(currentSentence))
            {
                sentences.Add(currentSentence);
            }

            return sentences;
        }
    }

    /// <summary>
    /// 章节结尾分析结果
    /// </summary>
    public class ChapterEndingAnalysis
    {
        public string OriginalContent { get; set; } = string.Empty;
        public string EndingContent { get; set; } = string.Empty;
        public bool IsComplete { get; set; }
        public List<string> Issues { get; set; } = new();
        public string AIAnalysis { get; set; } = string.Empty;
        public DateTime AnalyzedAt { get; set; }
    }

    // ChapterContext 已在其他地方定义
}
